package cn.kust.serviceusercenter.controller;


import cn.kust.microtourismcommon.constant.CommonStatusEnum;
import cn.kust.microtourismcommon.pojo.dto.MicroTourismUser;
import cn.kust.microtourismcommon.pojo.dto.ResponseResult;
import cn.kust.microtourismcommon.pojo.dto.TokenResult;
import cn.kust.microtourismcommon.pojo.dto.UserIdDTO;
import cn.kust.microtourismcommon.pojo.request.VerificationCodeDTO;
import cn.kust.microtourismcommon.util.JwtUtils;
import cn.kust.serviceusercenter.service.IUserService;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author WY
 * @data 2022/7/5 20:38
 **/
@RestController
@RequestMapping("/userCenter")
@Slf4j
public class UserController {

    @Autowired
    private IUserService userService;

    // 插入手机用户
    @PostMapping("/user")
    public ResponseResult login(@RequestBody VerificationCodeDTO verificationCodeDTO) {
        String userPhone = verificationCodeDTO.getUserPhone();
        log.debug("手机号：" + userPhone);
        return userService.loginOrRegister(userPhone);
    }

    // 根据手机号查询用户信息
    @GetMapping("/user/{phone}")
    public ResponseResult getUser(@PathVariable("phone") String userPhone) {

        return userService.getUserByPhone(userPhone);

    }

    // 根据用户id查询用户名和头像
    @RequestMapping(value = "/user/user-name-avatar/{userId}", method = RequestMethod.GET)
    public ResponseResult getUser(@PathVariable("userId") Long userId) {
        String userid = Long.toString(userId);
        return userService.getUserNameAvatar(userid);

    }

    // 根据id列表查询用户的用户名和头像
    @RequestMapping(value = "/user/list/name-avatar", method = RequestMethod.POST)
    public ResponseResult getUserNameAvatarList(@RequestBody UserIdDTO userIdDTO) {

        log.debug(userIdDTO.toString());
        List<Long> userIds = userIdDTO.getUserIdList();
        if (userIds == null || userIds.size() == 0) {
            return ResponseResult.fail(CommonStatusEnum.USER_ID_LIST_EMPTY.getCode(), CommonStatusEnum.USER_ID_LIST_EMPTY.getValue());
        }
        return userService.getUserNameAvatarListById(userIds);
    }

    //用户信息分页查询
    @RequestMapping(value = "/users/{pageNum}/{pageSize}", method = RequestMethod.GET)
    public ResponseResult getUsersPage(@PathVariable("pageNum") int pageNum, @PathVariable("pageSize")
            int pageSize) {
        if (pageNum != 0 || pageSize != 0) {
            return userService.getUsersPage(pageNum, pageSize);
        }
        return null;
    }


    // 添加用户
    @RequestMapping(value = "/user/add", method = RequestMethod.PUT)
    public ResponseResult addUser(@RequestBody MicroTourismUser user) {
        if (user.getId() != null || user.getUserPhone() == null || user.getUserName().isEmpty() || user.getUserName() == null){
            return ResponseResult.fail(CommonStatusEnum.FOLLOW_INDEX_ERROR.getCode(),CommonStatusEnum.FOLLOW_INDEX_ERROR.getValue());
        }

        return userService.insertUser(user);
    }

    //删除用户
    @RequestMapping(value = "/user/delete/{userid}", method = RequestMethod.DELETE)
    public ResponseResult deleteUserById(@PathVariable("userid") String userid) {
        //这里已经验证过了id，id保证合法
        log.debug(userid.toString());
        // 以后需要特殊的token身份才能删除数据
        long userId = Long.parseLong(userid);
        return userService.deleteUserById(userId);

    }

    //修改用户信息
    @RequestMapping(value = "/user/update/{userid}", method = RequestMethod.POST)
    public ResponseResult updateUser(@PathVariable("userid") String userId, @RequestBody MicroTourismUser user , HttpServletRequest request) {
        System.out.println(userId);
        System.out.println(user.toString());

        if (userId == null || user == null){
            return ResponseResult.fail(CommonStatusEnum.FOLLOW_INDEX_ERROR.getCode(),CommonStatusEnum.FOLLOW_INDEX_ERROR.getValue());
        }
        // 检查修改的目标id是否和token信息中的id一致,不一致返回错误
        // 获取用户id
        TokenResult tokenResult = JwtUtils.parseRequestToken(request);
        String tokenuserId = tokenResult.getUserId();
        if(!tokenuserId.equals(userId)){
            return ResponseResult.fail(CommonStatusEnum.USER_TOKEN_ARGS_ERROR.getCode(),CommonStatusEnum.USER_TOKEN_ARGS_ERROR.getValue());
        }
        long userid = Long.parseLong(userId);

        return userService.updateUserInfo(userid,user);
    }


    //用户上传头像接口
    @RequestMapping(value = "/user/upload-avatar", method = RequestMethod.POST)
    public ResponseResult uploadAvatar(@RequestBody MultipartFile file, HttpServletRequest request) {
        // 获取用户id
        TokenResult tokenResult = JwtUtils.parseRequestToken(request);
        String userId = tokenResult.getUserId();
        if (userId != null & file != null) {
            return userService.updateUserAvatar(file, userId);
        }
        return ResponseResult.fail(CommonStatusEnum.ILLEGAL_URL_ERROR.getCode(), CommonStatusEnum.TOKEN_IS_EMPTY.getValue());

    }

    //用户上传背景图片接口
    @RequestMapping(value = "/user/upload-background", method = RequestMethod.POST)
    public ResponseResult uploadBackGround(@RequestBody MultipartFile file, HttpServletRequest request) {
        // 获取用户id
        TokenResult tokenResult = JwtUtils.parseRequestToken(request);
        String userId = tokenResult.getUserId();
        if (userId != null & file != null) {
            return userService.updateUserBackground(file, userId);
        }
        return ResponseResult.fail(CommonStatusEnum.ILLEGAL_URL_ERROR.getCode(), CommonStatusEnum.TOKEN_IS_EMPTY.getValue());

    }


}
